import axios from 'axios';

// 创建axios实例
const request = axios.create({
  // 从环境变量获取基础URL process.env.VITE_API_BASE_URL
  baseURL: import.meta.env.VITE_API_BASE_URL || '',
  timeout: 10000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
});

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    // 可以在这里添加认证token
    // const token = localStorage.getItem('token');
    // if (token) {
    //   config.headers.Authorization = `Bearer ${token}`;
    // }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    // 只返回响应数据部分
    return response.data;
  },
  (error) => {
    // 统一错误处理
    console.error('Request error', 'method:', error.config?.method, 'url:', error.config?.url, 'params:', error.config?.params, 'data:', error.config?.data, 'error:', error.message);
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 处理未授权错误
          console.error('Unauthorized', 'method:', error.config?.method, 'url:', error.config?.url);
          // router.push('/login');
          break;
        case 404:
          console.error('Resource not found', 'method:', error.config?.method, 'url:', error.config?.url);
          break;
        case 500:
          console.error('Server error', 'method:', error.config?.method, 'url:', error.config?.url);
          break;
        default:
          console.error('Error', error.response.status, 'method:', error.config?.method, 'url:', error.config?.url);
      }
    }
    return Promise.reject(error);
  }
);

/**
 * 文件上传方法
 * @param {string} url - 上传接口地址
 * @param {File} file - 要上传的文件对象
 * @param {Object} [data={}] - 额外的表单数据
 * @param {Function} [onProgress] - 上传进度回调函数 (progress) => {}
 * @returns {Promise}
 */
const upload = (url, file, data = {}, onProgress) => {
  const formData = new FormData();
  formData.append('file', file);

  // 添加额外表单数据
  Object.entries(data).forEach(([key, value]) => {
    formData.append(key, value);
  });

  return request.post(url, formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    onUploadProgress: progressEvent => {
      const progress = Math.round((progressEvent.loaded * 100) / (progressEvent.total || 1));
      if (onProgress && typeof onProgress === 'function') {
        onProgress(progress);
      }
    }
  });
};

/**
 * 统一请求方法
 * @param {string} method - 请求方法 GET|POST|PUT|DELETE 等
 * @param {string} url - 请求地址
 * @param {Object} [options={}] - 请求配置
 * @param {Object} [options.params] - URL参数
 * @param {Object} [options.data] - 请求体数据
 * @param {Object} [options.config] - 额外配置
 * @returns {Promise}
 */
const requestMethod = (method, url, {params = {}, data = {}, ...config} = {}) => {
  return request({
    method,
    url,
    params,
    data,
    ...config
  });
};

// HTTP请求方法集合
export const http = {
  get: (url, options) => requestMethod('GET', url, options),
  post: (url, options) => requestMethod('POST', url, options),
  put: (url, options) => requestMethod('PUT', url, options),
  delete: (url, options) => requestMethod('DELETE', url, options),
  upload: upload
};

export default http;